<script lang="ts" setup name="GpBaiduMapPage">
// import type { XuanXiaoTeach } from '@/api/designer/model'
import { useScript } from '@/hooks/useScript'
import { nextTick, onMounted, ref, unref } from 'vue'

// const props = defineProps<{
//   width: string | number
//   items?: XuanXiaoTeach[]
// height: {
//   type: String,
//   default: '100%'
// },
// latlng: String,
// id: String,
// name: String,
// address: String,
// fullAddress: String,
// }>()

const BAI_DU_MAP_INIT_URL
  = 'https://api.map.baidu.com/api?v=2.0&ak=KsmWoo221U1niQ2R9WnlXbap7yzDGDM6'

const BAI_DU_MAP_URL
  = 'https://api.map.baidu.com/getscript?v=2.0&ak=KsmWoo221U1niQ2R9WnlXbap7yzDGDM6&services=&t=20190102133327'

// const emit = defineEmits<{
//   (even: 'update', latlng: any, areaId: any, areaName: any, address: any, fullAddress: any);
// }>()

// initMap();

// 定位坐标
const location = ref<any>()
const info = ref({
  areaId: '', // 地区 id
  areaName: '', // 地区名称
  address: '', // 地址
  lnglat: '113.331075,23.112047', // 坐标
  loading: false, // 智能提示加载状态
  options: [] as any[], // 智能提示数据源
})
// const lists = computed(() => props.items)

const lists = ref([
  { lng: '113.332665', lat: '23.138009', name: '正佳广场' },
  { lng: '113.372739', lat: '23.134134', name: '天河公园' },
  { lng: '113.32816', lat: '23.111778', name: '广州国际媒体港' },
  { lng: '113.34675', lat: '23.112617', name: '珠江啤酒博物馆琶醍A区停车场' },
  { lng: '113.331228', lat: ' 23.156485', name: '广州东站' },
  { lng: '113.296445', lat: ' 23.157814', name: '白云仙馆' },
])
const wrapRef = ref<HTMLDivElement | null>(null)
const { toPromise: toInit } = useScript({ src: BAI_DU_MAP_INIT_URL })
const { toPromise } = useScript({ src: BAI_DU_MAP_URL })

// 地图
const _map = ref<any>()
const _localSearch = ref<any>()

const cityPoint = ref(null) // 中心点
async function initMap() {
  await toInit()
  await toPromise()
  await nextTick()
  const wrapEl = unref(wrapRef)

  if (!wrapEl) 
    return
  const BMap = (window as any).BMap
  const map = new BMap.Map(wrapEl, { enableMapClick: false })
  const defPoint = new BMap.Point(113.331075, 23.112047) // 默认中心点--广州塔

  if (lists.value && lists.value.length > 0 && lists.value[1] && lists.value[1].lng && lists.value[1].lat) {
    cityPoint.value = new BMap.Point(Number.parseFloat(lists.value[1].lng), Number.parseFloat(lists.value[1].lat))
    location.value = cityPoint.value
  }

  // 右键菜单
  const contextMenu = new BMap.ContextMenu()
  const txtMenuItem = [
    {
      text: '放大',
      callback() {
        map.zoomIn()
      },
    },
    {
      text: '缩小',
      callback() {
        map.zoomOut()
      },
    },
    {
      text: '放置到最大级',
      callback() {
        map.setZoom(18)
      },
    },
    {
      text: '查看全国',
      callback() {
        map.setZoom(4)
      },
    },
    {
      text: '在此添加标注',
      callback(p: any) {
        map.clearOverlays()
        addMarker(p)
        location.value = p
      },
    },
    {
      text: '清除标注',
      callback() {
        map.clearOverlays()
        location.value = null
      },
    },
  ]

  for (let i = 0; i < txtMenuItem.length; i++) {
    contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100))
    if (i === 1 || i === 3) {
      contextMenu.addSeparator()
    }
  }

  map.addContextMenu(contextMenu)
  map.centerAndZoom(cityPoint.value || defPoint, cityPoint.value ? 13 : 19)
  map.enableScrollWheelZoom(true)
  map.addControl(new BMap.NavigationControl()) // 左侧控件

  // _localSearch.value = new BMap.LocalSearch(map, { onSearchComplete: searchComplete });
  _localSearch.value = new BMap.LocalSearch(map)
  _map.value = map

  if (lists.value && lists.value.length) {
    lists.value.forEach((p) => {
      if (p.lng && p.lat) {
        const pp = new BMap.Point(Number.parseFloat(p!.lng), Number.parseFloat(p!.lat))
        addMarker(pp)
      }
    })
  }
}

onMounted(() => {
  initMap()
})

/**
 * 搜索提示回调
 */
// function searchComplete(results) {
// console.log('results', results);
// }

// 添加标注
function addMarker(point: any) {
  location.value = point
  // let icon = (point.lat === cityPoint.value!.lat && point.lng === cityPoint.value!.lng) 
  // ? 'https://gp.91goodschool.com/images/large_blue.gif' 
  // : 'https://api.map.baidu.com/images/blank.gif'
  
  const BMap = (window as any).BMap
  const marker = new BMap.Marker(point, {
    icon: new BMap.Icon(
      'https://gp.91goodschool.com/images/large_blue.gif',
      new BMap.Size(25, 37),
    ),
    offset: new BMap.Size(0, -18),
    // text: new BMap.Text().text("百度地图SDK") //文字内容
    //     .bgColor(0xAAFFFF00) //背景色
    //     .fontSize(24) //字号
    //     .fontColor(0xFFFF00FF) //文字颜色
    //     .rotate(-30) //旋转角度
  })

  marker.addEventListener('click', () => {
    location.value = point
  })

  // _map.value.clearOverlays()
  _map.value.addOverlay(marker)
}

// 选择地址
function handleSelectAddress(e: any) {
  const f = info.value.options.find(c => c.title === e)
  if (f) {
    const BMap = (window as any).BMap
    const p = new BMap.Point(f.lng, f.lat)
    _map.value.centerAndZoom(p, 19)
    addMarker(p)
    location.value = p
  }
}

// function handleOk() {
//   let latlng = '';
//   if (location.value && location.value.lat && location.value.lng) {
//     latlng = location.value.lat + ',' + location.value.lng;
//   }

//   info.value.latlng = latlng;
//   emit('update', latlng, ProCityArea.value, info.value.areaName, info.value.address, info.value.areaName + '-' + info.value.address);
// }

// const ProCityArea = ref([])
// function handleText(val: any) {
//   console.log(val.value);
//   info.value.areaName = val.value
// }
// function handleValue(value: any) {
//   console.log(value);
//   info.value.areaId = value[1];
//   ProCityArea.value = value;
// }

defineExpose({ handleSelectAddress })
</script>

<template>
  <div class="w-full">
    <div ref="wrapRef" :style="{ width: `100%`, aspectRatio: 1.777 }" />
  </div>
</template>
